import axios from './index';
import { AxiosRequestConfig, AxiosResponse } from './types'

interface User {
    name: string
    password: string
}

let user: User = { name: 'zhufeng', password: '12345678' }
let baseURL = 'www.baidu.com'

console.time('cost');
// 先加的后执行
axios.interceptors.request.use((config: AxiosRequestConfig): AxiosRequestConfig => {
    config.headers!.name += 1

    return config
})
let request = axios.interceptors.request.use((config: AxiosRequestConfig): AxiosRequestConfig => {
    config.headers!.name += 2
    return config
})
axios.interceptors.request.use((config: AxiosRequestConfig): AxiosRequestConfig | Promise<AxiosRequestConfig> => {
    // 拦截器可以同步也可以异步
    return new Promise(function(resolve){
        setTimeout(() => {
            config.headers!.name += 3
            resolve(config)
        }, 300)
    })
})
axios.interceptors.request.eject(request); // 可以弹出
// 先加的先执行
let response = axios.interceptors.response.use((response: AxiosResponse): AxiosResponse => {
    response.data.name += 1
    return response
})
axios.interceptors.response.use((response: AxiosResponse): AxiosResponse => {
    response.data.name += 2
    return response
})
axios.interceptors.response.use((response: AxiosResponse): AxiosResponse => {
    response.data.name += 3
    return response
})
axios.interceptors.response.eject(response); // 可以弹出
console.timeEnd('cost')

const CancelToken = axios.CancelToken;
const source = CancelToken.source();
const isCancel = axios.isCancel;

axios({
    method: 'get',
    url: baseURL + '/get',
    params: user
}).then((response: AxiosResponse<User>) => {
    return response.data
}).then((data: User) => {
    console.log(data);
}).catch((error: any) => {
    console.log(error);
});

axios({
    method: 'post',
    url: baseURL + '/post',
    headers: {
        'constent-type': 'application/json',
        "name": 'name'
    },
    cancelToken: source.token,
    data: user
}).catch(err => {
    if(isCancel(err)) {
        console.log('取消')
    } else {
        console.log(err)
    }
})
source.cancel('取消请求');